#define _CRT_SECURE_NO_WARNINGS 1

  struct ListNode {
      int val;
      ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };
 
class Solution {
public:
    void Reverse(ListNode* start, ListNode* end)
    {
        ListNode* prev = start, * cur = start->next;
        while (prev != end)
        {
            ListNode* next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
    }
    ListNode* reverseKGroup(ListNode* head, int k)
    {
        if (head == nullptr || head->next == nullptr || k == 1) return head;
        ListNode* newhead = new ListNode(-1, head);
        ListNode* prev = newhead;
        ListNode* start = prev->next;
        while (start)
        {
            ListNode* end = start;
            for (int i = 1;i < k;++i)
            {
                end = end->next;
                if (end == nullptr)
                {
                    return newhead->next;
                }
            }
            ListNode* next = end->next;
            Reverse(start, end);
            prev->next = end;
            prev = start;
            start->next = next;
            start = next;
        }
        return newhead->next;
    }
};